'use strict';

const Service = require('egg').Service;

class MessageService extends Service {
	/*
     * 获取消息
     * */
	async findMsg({ id, page = 1, limit = 10 }, select = null) {
		const { ctx } = this;

		if (id) {
			return await ctx.model.Message.findById(id).select(select);
		} else {
			const sendee = ctx.state.user._id;
			const res = await ctx.model.Message
				.find({ sendee })
				.skip(Number(page) - 1)
				.limit(Number(limit))
				.select(select);
			const count = await ctx.model.Message.find({ sendee }).count();
			return {
				count,
				page,
				list: res
			};
		}
	}
	/**
     * 发送消息
	 * @param {String} username -用户名
	 * @param {String} id -用户id
	 * @param {String} content -消息内容
	 * @param {String} title -消息标题
	 * @param {String} type -消息类型
	 *
     */
	async create({ username, id, content, title, type }) {
		const { ctx } = this;
		if (id) {
			return await ctx.model.Message.create({
				content,
				type,
				title,
				auth: ctx.state.user._id,
				sendee: id
			});
		}
		const sendee = await ctx.model.User.findOne({ username });
		if (sendee) {
			return await ctx.model.Message.create({
				content,
				type,
				title,
				auth: ctx.state.user._id,
				sendee: sendee.id
			});
		} else {
			return null;
		}
	}

	/**
     * 删除消息
     *
     * @param {String} id -消息ID
     */
	async destroy(id) {
		const { ctx } = this;

		const message = await ctx.model.Message.findById(id);
		if (!message) {
			ctx.throw(404, '消息不存在或已被删除', {
				code: 'message_not'
			});
		}
		// 权限验证
		await ctx.powerValidate(message.auth._id);

		const res = await ctx.model.Message.findByIdAndRemove(id);
		return res;
	}

	/**
     * 消息标记为已读
     *
     * @param {String} id -消息ID
     */
	async read(id) {
		const { ctx } = this;

		const message = await ctx.model.Message.findById(id);
		if (!message) {
			ctx.throw(404, '消息不存在或已被删除', {
				code: 'message_not'
			});
		}

		const msgState = {
			state: 1,
			updateAt: Date.now()
		};
		const res = await ctx.model.Message.findByIdAndUpdate(id, msgState);

		return res;
	}
	/**
     * 消息全部标记为已读
     *
     */
	async readAll() {
		const { ctx } = this;
		const msgState = {
			state: 1,
			updateAt: Date.now()
		};
		const res = await ctx.model.Message.update({ auth: ctx.state.user._id, state: 0 }, msgState, {
			multi: false,
			overwrite: true
		});
		return res;
	}
}
module.exports = MessageService;
